/**
 * $Revision: 1.1 $
 * $Date: 2010/06/28 07:03:13 $
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Lesser Public License (LGPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.spark.search;

import org.jivesoftware.Spark;
import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.Workspace;
import org.jivesoftware.spark.component.IconTextField;
import org.jivesoftware.spark.util.ResourceUtils;


import cn.newgrand.netcall.imp.search.contact.ContactSearchResultPanel;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.util.Collection;

public class SearchService extends JPanel {
	private IconTextField findField;
	private Image backgroundImage;
	private boolean newSearch;

	private Searchable activeSearchable;
	private final ContactSearchResultPanel contactSearchResult;

	public SearchService() {
		setLayout(new GridBagLayout());
		
		findField = new IconTextField(SparkRes
				.getImageIcon(SparkRes.SEARCH_USER_16x16));

		backgroundImage = Default.getImageIcon(
				Default.SEARCH_BAR_BACKGROUND).getImage();

		final JLabel findLabel = new JLabel();

		ResourceUtils.resLabel(findLabel, findField, Res
				.getString("label.find"));

		// add(findLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
		// GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5,
		// 5), 0, 0));

		if (Spark.isMac()) {
			add(findField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0,
					GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
					new Insets(2, 5, 4, 30), 0, 0));
		} else {
			add(findField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0,
					GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
					new Insets(2, 5, 4, 5), 0, 0));
		}

		// Check for secure connection
		if (SparkManager.getConnection().isSecureConnection()) {
//			final JLabel lockLabel = new JLabel();
//			lockLabel.setHorizontalTextPosition(JLabel.LEFT);
//			lockLabel.setIcon(SparkRes.getImageIcon(SparkRes.LOCK_16x16));
//			if (Spark.isMac()) {
//				add(lockLabel, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0,
//						GridBagConstraints.WEST, GridBagConstraints.NONE,
//						new Insets(5, 0, 5, 15), 0, 0));
//
//			} else {
//				add(lockLabel, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0,
//						GridBagConstraints.WEST, GridBagConstraints.NONE,
//						new Insets(5, 0, 5, 5), 0, 0));
//			}
//			lockLabel.setToolTipText(Res.getString("message.spark.secure"));
		}

		findField.setToolTipText(Res.getString("message.search.for.contacts"));
		findField.setBorder(BorderFactory.createLineBorder(new Color(220 ,220,220)));

		
		
		findField.addFocusListener(focusListener);
		findField.getTextComponent().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				// if (newSearch) {
				// findField.setText("");
				// findField.getTextComponent().setForeground((Color)
				// UIManager.get("TextField.foreground"));
				// newSearch = false;
				// }
			}
		});
		findField.getImageComponent().addMouseListener(findFieldMouseListener);
		
		contactSearchResult = SparkManager.getContactManager().getContactSearchManager().getContactSearchResultPanel();
		SparkManager.getMainWindow().getLayeredPane().add(contactSearchResult,JLayeredPane.POPUP_LAYER);
		contactSearchResult.initListenerForLocation(findField.getTextComponent());
		
		Workspace workspace = SparkManager.getWorkspace();
		workspace.add(this, new GridBagConstraints(0, 4, 1, 1, 1.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
				new Insets(0, 0, 0, 0), 0, 0));
		workspace.invalidate();
		workspace.validate();
		workspace.repaint();

		
	}

	public void setActiveSearchService(final Searchable searchable) {
		this.activeSearchable = searchable;

		newSearch = true;
		// findField.requestFocus();
		findField.getTextComponent().setForeground(
				(Color) UIManager.get("TextField.lightforeground"));
		findField.setIcon(searchable.getIcon());
		findField.setText(searchable.getDefaultText());
		findField.setToolTipText(searchable.getToolTip());

		findField.getTextComponent().addFocusListener(findFieldTextFocusListener);
	}

	public void paintComponent(Graphics g) {
		double scaleX = getWidth() / (double) backgroundImage.getWidth(null);
		double scaleY = getHeight() / (double) backgroundImage.getHeight(null);
		AffineTransform xform = AffineTransform
				.getScaleInstance(scaleX, scaleY);
		((Graphics2D) g).drawImage(backgroundImage, xform, this);
	}

	public IconTextField getFindField() {
		return findField;
	}

	public void setBackgroundImage(Image image) {
		this.backgroundImage = image;
	}
	
	final FocusListener findFieldTextFocusListener = new FocusListener() {
		public void focusGained(FocusEvent e) {
			if (findField.getText().equals(activeSearchable.getDefaultText()))
				findField.setText("");
			else {
				if (!findField.getText().equals("")) {
//					 contactSearchResult.showInMainWin(findField.getText());
				}
			}
		}
		/**
		 * 在快速查找过程中，输入字母焦点已经在查询的结果上面，即查找输入框已经失去焦点
		 * 如果想在选择查找的用户并弹出聊天窗后，再使查询的窗口恢复到默认文字
		 * 那么就需要
		 * 
		 */
		public void focusLost(FocusEvent e) {
//			System.out.println("a"+findField.getText()+"a");
			if (null == findField.getText()
					|| findField.getText().equals("")) {
				findField.getTextComponent().setForeground(
						(Color) UIManager.get("TextField.lightforeground"));
				findField.setText(activeSearchable.getDefaultText());
			}
		}
	};

	final MouseListener findFieldMouseListener = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
			Collection<Searchable> searchables = SparkManager
					.getSearchManager().getSearchServices();
			if (searchables.size() <= 1) {
				return;
			}

			// Show popup
			final JPopupMenu popup = new JPopupMenu();
			for (final Searchable searchable : searchables) {
				Action action = new AbstractAction() {
					public void actionPerformed(ActionEvent e) {
						setActiveSearchService(searchable);
					}
				};
				action.putValue(Action.SMALL_ICON, searchable.getIcon());
				action.putValue(Action.NAME, searchable.getName());
				popup.add(action);
			}
			popup.show(findField, 0, findField.getHeight());
		}
	};
		
	final FocusListener focusListener = new FocusListener() {
		
		@Override
		public void focusLost(FocusEvent arg0) {
			if(!contactSearchResult.isFocusOwner()){
				contactSearchResult.setVisible(false);
			}
		}
		
		@Override
		public void focusGained(FocusEvent arg0) {
			// TODO Auto-generated method stub
			
		}
	};
}
